package chapter04.part02;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 提供多连接服务
 * 
 * 1. 循环监听提供 Socket
 * 2. 为每一个连接提供 Thread (并不能满足高性能服务器的要求 可使用 nio 下的异步socket)
 * 
 * @author insight
 * @since 2021/8/29
 */
public class MultiClientTest {
    public static void main(String[] args) throws IOException {
        try (ServerSocket serverSocket = new ServerSocket(8080)) {
            while (true) {
                Socket incoming = serverSocket.accept();
                ThreadEchoHandler r =
                        new ThreadEchoHandler(incoming);
                Thread t = new Thread(r);
                t.start();
            }
        }
    }

    static class ThreadEchoHandler implements Runnable {
        private Socket incoming;
        private String name;

        public ThreadEchoHandler(Socket incoming) {
            this.incoming = incoming;
        }
        
        @Override
        public void run() {
            name = Thread.currentThread().getName();
            System.out.println(name + " Successfully Connected to ServerSocket...");
            // 接收 & 返回数据
            try (Scanner in = new Scanner(incoming.getInputStream(),
                    StandardCharsets.UTF_8);
                 PrintWriter out = new PrintWriter(
                         new OutputStreamWriter(incoming.getOutputStream(), StandardCharsets.UTF_8), true)) {
                out.println("Hello, Here is insight's ServerDemo!");

                boolean online = true;
                while (online && in.hasNextLine()) {
                    String command = in.nextLine();
                    String content = "Echo: " + command;
                    System.out.println(content);
                    out.println(content);
                    if ("exit".equals(command.trim().toLowerCase())) {
                        online = false;
                        out.println("GoodBye");
                    }
                }
                incoming.close();
                
                System.out.println(name + " Disconnect From ServerSocket...");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}